package com.msb.internalcommon.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.msb.internalcommon.dto.TokenResult;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: jiudianliu
 * @Date: 2023/5/24 - 05 - 24 - 8:37
 * @Description: com.msb.internalcommon.util
 * @version: 1.0
 */
public class JwtUtils {

    //  盐
    private static final String SIGN = "RZ XIS 1999" ;

    //手机号（乘客和司机）
    private static final String JWT_KEY_PONE = "Phone" ;

    //身份验证乘客1和司机2
    private static  final String JWT_KEY_IDENTITY = "identity" ;


    //
    private static  final String JWT_TOKEN_TYPE = "tokenType" ;


    //  生成token
    public static String generatorToken( String passengerPhone , String identity , String tokenType){
        Map<String,String> map = new HashMap<>() ;
        map.put(JWT_KEY_PONE , passengerPhone) ;
        map.put(JWT_KEY_IDENTITY , identity) ;
        map.put(JWT_TOKEN_TYPE , tokenType) ;
        //  token过期时间
        Calendar calendar = Calendar.getInstance() ;
        //  给当前日期加一天过期
        map.put(JWT_TOKEN_TYPE , Calendar.getInstance().getTime().toString()) ;
        JWTCreator.Builder builder = JWT.create() ;
        //遍历map逐步放Builder里
        map.forEach(
                builder::withClaim
        );

        //  整合过期时间
        //builder.withExpiresAt(time) ;

        //生成token
        String sign = builder.sign(Algorithm.HMAC256(SIGN)) ;
        return sign ;
    }

    //  解析token
    public static TokenResult parseToken(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token) ;
        String phone = verify.getClaim(JWT_KEY_PONE).asString() ;
        String identity = verify.getClaim(JWT_KEY_IDENTITY).asString() ;

        //创建解析的对象
        TokenResult tokenResult = new TokenResult() ;
        tokenResult.setPhone(phone) ;
        tokenResult.setIdentity(identity) ;
        return tokenResult ;
    }


    //解析refreshToken  主要判断Token是否异常
    public static TokenResult checkToken(String token){
        TokenResult tokenResult = null ;
        try{
            tokenResult = parseToken(token) ;
        }catch (Exception e) {

        }
        return tokenResult ;
    }


    public static void main(String[] args) {
        String s = generatorToken("15506483326" , "1" , "accessToken");
        System.out.println("生成的token：" + s);
        System.out.println("解析token-------------------------");
        TokenResult tokenResult = parseToken(s) ;
        System.out.println("手机号： " + tokenResult.getPhone());
        System.out.println("身份： " + tokenResult.getIdentity());
    }
}
